using System;
using System.Threading;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Configuration;
using System.Messaging;

namespace Derrick.Web
{
    public class SIServer : Server
    {
        ServerInterfaceConfig config;

        public SIServer(ServerInterfaceConfig c)
            : base(Dns.GetHostEntry(IPAddress.Parse(c.BindTo)).AddressList[0], c.Port, c.Authentication)
        {
            config = c;

        }

        public override Response HandleRequest(Request request, DateTime lastUpdate)
        {
            if (_traceSwitch == null)
            {
                _traceSwitch = new TraceSwitch("TraceLevelSwitch", "Comet Tracing");
            }

            ///TO DO: add in method to send response in JSON
            ///Derrick Lau - Feb. 3, 2012
            //Console.WriteLine("SIServer HandleRequest(). " + request.Url);
            Trace.WriteLine("SIServer HandleRequest(). " + request.Url);

            //Console.WriteLine("---");
            Trace.WriteLine("---");
            //Console.WriteLine("\""+request.Body+"\"");
            Trace.WriteLine("\"" + request.Body + "\"");
            //Console.WriteLine("---");
            Trace.WriteLine("---");

            Trace.WriteLineIf(_traceSwitch.TraceInfo, "Inside SIServer.HandleRequest()...");

            try
            {

                #region Process HTTP message as XML
                //Picks up message from HTTP:
                XmlSerializer s = new XmlSerializer(typeof(SIRequest));

                MemoryStream mem = new MemoryStream();
                mem.Write(System.Text.Encoding.ASCII.GetBytes(request.Body), 0, request.Body.Length);
                mem.Seek(0, 0);

                //Loads message into object for processing.
                SIRequest data = (SIRequest)s.Deserialize(mem);
                #endregion Process HTTP message as XML

                #region Process HTTP message as JSON




                #endregion Process HTTP message as JSON

                //Monitor.Wait(_lockObject);
                //_semaphore.WaitOne();

                //process message, do stuff here!
                string responseMsg = "<?xml version='1.0'?><Response>";


                //foreach (string msg in data.Messages)
                //{
                //    responseMsg += "<Message>" + msg + " at COMET server.</Message>";
                //}

                lock (_lockObj)
                {
                    if (QueueMessage.Instance.LastUpdated > lastUpdate)
                    {
                        responseMsg += "<Message>" + QueueMessage.Instance.Message + "</Message>";
                    }
                }

                //responseMsg += "<Message>Unblocked</Message>";
                responseMsg += "</Response>";

                Trace.Flush();

                return Response.GetHtmlResponse(responseMsg, QueueMessage.Instance.LastUpdated);

            } catch (Exception ex) {
                Console.WriteLine("Error parsing xml: " + ex.Message);
                Trace.WriteLineIf(_traceSwitch.TraceError, "Inside SIServer.HandleRequest().  Exception thrown: " + ex.ToString());
                Trace.Flush();
                return Response.GetHtmlResponse("Error parsing xml: " + ex.Message, QueueMessage.Instance.LastUpdated);
            }
        }



        

        [XmlRoot("Request")]
        public class SIRequest
        {
            public enum CommandType
            {
                Queue,
                Remove
            }

            public struct MessageData
            {
                public string Message;
            }

            public CommandType Command = CommandType.Queue;
            public string User = "";

            [XmlElement("Message")]
            public string[] Messages;
        }


    }
}
